package com.yami.shop.im.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.im.bean.ImMsgBizEmployeeRecent;
import com.yami.shop.im.bean.ImMsgBizUser;
import com.yami.shop.im.bean.ImMsgBizUserHistory;
import com.yami.shop.im.constants.Constant;
import com.yami.shop.im.constants.SendType;
import com.yami.shop.im.hanlder.SecurityHandler;
import com.yami.shop.im.service.ImMsgBizEmployeeRecentService;
import com.yami.shop.im.service.ImMsgBizUserHistoryService;
import com.yami.shop.im.service.ImMsgBizUserService;
import com.yami.shop.im.vo.Conversation;
import com.yami.shop.security.multishop.model.YamiShopUser;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Lzk
 */
@RestController
@RequestMapping("/p/shop")
@Tag(name = "店铺聊天接口")
public class ShopController {

    @Autowired
    private UserService userService;
    @Autowired
    private ShopDetailService shopDetailService;
    @Autowired
    private ImMsgBizEmployeeRecentService imMsgBizEmployeeRecentService;
    @Autowired
    private ImMsgBizUserService imMsgBizUserService;
    @Autowired
    private ImMsgBizUserHistoryService imMsgBizUserHistoryService;
    @Autowired
    private SecurityHandler securityHandler;

    @PostMapping("/conversations")
    @Operation(summary =  "最后的对话信息列表项", description = "获取最后的对话信息列表项")
    public ServerResponseEntity<Page<Conversation>> conversations(PageParam<ImMsgBizEmployeeRecent> pageParam) {
        YamiShopUser yamiShopUser = securityHandler.getShopUser(null);
        Page<ImMsgBizEmployeeRecent> imMsgBizEmployeeRecentPage = imMsgBizEmployeeRecentService.page(pageParam, new LambdaQueryWrapper<ImMsgBizEmployeeRecent>()
                .eq(ImMsgBizEmployeeRecent::getSendType, SendType.SHOP).eq(ImMsgBizEmployeeRecent::getBizId, yamiShopUser.getShopId())
//                .ne(ImMsgBizEmployeeRecent::getStatus,-1)
                .and(wrapper -> wrapper.eq(ImMsgBizEmployeeRecent::getEmployeeId, yamiShopUser.getEmployeeId())
                        .or(wrapper1 -> wrapper1.eq(ImMsgBizEmployeeRecent::getEmployeeId,yamiShopUser.getShopId()).eq(ImMsgBizEmployeeRecent::getStatus,0))).orderByDesc(ImMsgBizEmployeeRecent::getUpdateTime));
        List<ImMsgBizEmployeeRecent> imMsgBizEmployeeRecentList = imMsgBizEmployeeRecentPage.getRecords();
        List<ImMsgBizEmployeeRecent> filter = imMsgBizEmployeeRecentList.stream().filter(recent -> Objects.equals(recent.getStatus(), 1)).collect(Collectors.toList());
        Map<String, ImMsgBizEmployeeRecent> recentMap = filter.stream().collect(Collectors.toMap(ImMsgBizEmployeeRecent::getUserId,recent -> recent));
        List<Conversation> conversations = new ArrayList<>();
        List<ImMsgBizEmployeeRecent> updateRecentList = new ArrayList<>();
        List<ImMsgBizUserHistory> updateHistoryList = new ArrayList<>();
        for (ImMsgBizEmployeeRecent imMsgBizEmployeeRecent : imMsgBizEmployeeRecentList) {
            if(Objects.equals(imMsgBizEmployeeRecent.getStatus(), 0)){
                imMsgBizEmployeeRecent.setEmployeeId(yamiShopUser.getEmployeeId());
                imMsgBizEmployeeRecent.setStatus(1);
                // 在接入一个新的用户时，可能存在其他的客服也接收过，所以此时要把其他的客服失效掉
                if(recentMap.containsKey(imMsgBizEmployeeRecent.getUserId())){
                    // 删除当前信息
                    imMsgBizEmployeeRecentService.removeById(imMsgBizEmployeeRecent);
                    continue;
                }else {
                    updateRecentList.add(imMsgBizEmployeeRecent);
                    List<ImMsgBizUserHistory> historyList = imMsgBizUserHistoryService.list(Wrappers.lambdaQuery(ImMsgBizUserHistory.class).eq(ImMsgBizUserHistory::getSendType, SendType.SHOP).eq(ImMsgBizUserHistory::getBizId, imMsgBizEmployeeRecent.getBizId())
                            .eq(ImMsgBizUserHistory::getEmployeeId, imMsgBizEmployeeRecent.getBizId()).eq(ImMsgBizUserHistory::getUserId, imMsgBizEmployeeRecent.getUserId()));
                    historyList.forEach(msgHistory -> msgHistory.setEmployeeId(imMsgBizEmployeeRecent.getEmployeeId()));
                    updateHistoryList.addAll(historyList);
                }
//                // 失效掉之前对接的客服信息
//                imMsgBizEmployeeRecentService.update(new LambdaUpdateWrapper<ImMsgBizEmployeeRecent>()
//                        .set(ImMsgBizEmployeeRecent::getStatus,-1)
//                        .ne(ImMsgBizEmployeeRecent::getEmployeeId,yamiShopUser.getEmployeeId())
//                        .eq(ImMsgBizEmployeeRecent::getSendType, SendType.SHOP).eq(ImMsgBizEmployeeRecent::getBizId, yamiShopUser.getShopId())
//                        .eq(ImMsgBizEmployeeRecent::getStatus,1)
//                        .eq(ImMsgBizEmployeeRecent::getUserId,imMsgBizEmployeeRecent.getUserId()));
            }
            ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(imMsgBizEmployeeRecent.getBizId());
            if (shopDetail != null && shopDetail.getShopStatus() != null) {
                ImMsgBizUserHistory imMsgBizUserHistory = imMsgBizUserHistoryService.getOne(new LambdaQueryWrapper<ImMsgBizUserHistory>().eq(ImMsgBizUserHistory::getSendType, SendType.SHOP).eq(ImMsgBizUserHistory::getBizId, imMsgBizEmployeeRecent.getBizId())
                        .eq(ImMsgBizUserHistory::getEmployeeId, imMsgBizEmployeeRecent.getEmployeeId()).eq(ImMsgBizUserHistory::getUserId, imMsgBizEmployeeRecent.getUserId()).orderByDesc(ImMsgBizUserHistory::getId), false);
                // 还没有客服接入过的新用户
                if (Objects.isNull(imMsgBizUserHistory)) {
                    imMsgBizUserHistory = imMsgBizUserHistoryService.getOne(new LambdaQueryWrapper<ImMsgBizUserHistory>().eq(ImMsgBizUserHistory::getSendType, SendType.SHOP).eq(ImMsgBizUserHistory::getBizId, imMsgBizEmployeeRecent.getBizId())
                            .eq(ImMsgBizUserHistory::getEmployeeId, imMsgBizEmployeeRecent.getBizId()).eq(ImMsgBizUserHistory::getUserId, imMsgBizEmployeeRecent.getUserId()).orderByDesc(ImMsgBizUserHistory::getId), false);

                }
                Conversation conversation = new Conversation();
                conversation.setChatType(imMsgBizUserHistory.getSendType());
                conversation.setShopId(imMsgBizEmployeeRecent.getBizId());
                conversation.setUserId(imMsgBizEmployeeRecent.getUserId());
                conversation.setLatestMsg(imMsgBizUserHistory.getContent());
                conversation.setUnread(imMsgBizEmployeeRecent.getEmployeeUnreadNum());
                // todo 东8区，不应该写死"+8"后续优化
                conversation.setTimestamp(imMsgBizUserHistory.getCreateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
                conversation.setTimeStr(DateUtil.format(Date.from(imMsgBizUserHistory.getCreateTime().atZone(ZoneId.systemDefault()).toInstant()), "yyyy/MM/dd"));
                conversation.setLatestMsgTime(Date.from(imMsgBizUserHistory.getCreateTime().atZone(ZoneId.systemDefault()).toInstant()));
                conversation.setType(imMsgBizUserHistory.getType());
                conversation.setShopStatus(shopDetail.getShopStatus());
                conversation.setEmployeeId(imMsgBizUserHistory.getEmployeeId());
                User user = userService.getUserByUserId(imMsgBizEmployeeRecent.getUserId());
                if (Objects.nonNull(user)) {
                    conversation.setPic(user.getPic());
                    conversation.setFriendName(user.getNickName());
                }else {
                    conversation.setFriendName("*用户已注销*");
                }
                Set<String> set2 = RedisUtil.keys(Constant.ONLINE_USER_PREFIX + conversation.getUserId() + Constant.UNDERLINE + "*");
                if (set2.isEmpty()) {
                    conversation.setIsOnline(false);
                } else {
                    conversation.setIsOnline(true);
                }
                conversations.add(conversation);
            }
        }
        if(CollectionUtils.isNotEmpty(updateRecentList)) {
            imMsgBizEmployeeRecentService.updateBatchById(updateRecentList);
        }
        if(CollectionUtils.isNotEmpty(updateHistoryList)) {
            imMsgBizUserHistoryService.updateBatchById(updateHistoryList);
        }
        Page<Conversation> conversationPage = new Page<>();
        BeanUtils.copyProperties(imMsgBizEmployeeRecentPage, conversationPage);
        conversationPage.setRecords(conversations);
        return ServerResponseEntity.success(conversationPage);
    }

    @GetMapping("/userInfo")
    @Operation(summary =  "获取用户信息", description = "获取用户信息")
    public ServerResponseEntity<List<Conversation>> userInfo(String userId) {
        List<Conversation> conversations = new ArrayList<>();
        User user = userService.getUserByUserId(userId);
        if (Objects.nonNull(user)) {
            Conversation conversation = new Conversation();
            conversation.setUserId(userId);
            conversation.setFriendName(user.getNickName());
            conversation.setPic(user.getPic());
            conversations.add(conversation);
        }
        return ServerResponseEntity.success(conversations);
    }
}
